package com.yykj.user.center.server.service.impl;

import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalStringUtil;
import com.yykj.user.center.client.dto.MedicalRecordBaseInfoDTO;
import com.yykj.user.center.server.dto.MedicalRecordInfoDTO;
import com.yykj.user.center.server.form.AddMedicalRecordForm;
import com.yykj.user.center.server.form.ExhortItemForm;
import com.yykj.user.center.server.model.*;
import com.yykj.user.center.server.repository.ExhortRepository;
import com.yykj.user.center.server.repository.MedicalRecordRepository;
import com.yykj.user.center.server.repository.patient.ConsultationInfoRepository;
import com.yykj.user.center.server.repository.patient.FileRepository;
import com.yykj.user.center.server.repository.patient.PatientCardInfoRepository;
import com.yykj.user.center.server.service.MedicalRecordService;
import com.yykj.user.center.server.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenl
 * @version 1.0
 * @date 2021/11/13 17:03
 */
@Service
public class MedicalRecordServiceImpl implements MedicalRecordService {
    @Autowired
    private ConsultationInfoRepository consultationInfoRepository;
    @Autowired
    private MedicalRecordRepository medicalRecordRepository;
    @Autowired
    private PatientCardInfoRepository patientCardInfoRepository;
    @Autowired
    private FileRepository fileRepository;
    @Autowired
    private ExhortRepository exhortRepository;

    @Transactional
    @Override
    public ConsultationInfoOrder create(AddMedicalRecordForm addMedicalRecordForm) {
        ConsultationInfoOrder consultationInfoOrder = consultationInfoRepository.findById(addMedicalRecordForm.getConsultationId()).orElse(null);
        if(consultationInfoOrder!=null){
            MedicalRecord medicalRecord = new MedicalRecord();
            String medicalRecordId = LocalStringUtil.getUUID();
            BeanUtils.copyProperties(consultationInfoOrder,medicalRecord);
            medicalRecord.setId(medicalRecordId);
            medicalRecord.setState(true);
            BeanUtils.copyProperties(addMedicalRecordForm,medicalRecord);
            String cardId = consultationInfoOrder.getPatientCardId();
            medicalRecord.setOrderType(consultationInfoOrder.getOrderType());
            PatientCardInfo patientCardInfo = patientCardInfoRepository.findById(cardId).orElse(null);
            if(patientCardInfo!=null){
                medicalRecord.setBirthday(patientCardInfo.getBirthday());
                medicalRecord.setReceiveTime(consultationInfoOrder.getReceiveTime());
                medicalRecord.setOrderNo(consultationInfoOrder.getOrderNo());
                medicalRecord.setCreateOrderTime(consultationInfoOrder.getCreateTime());
                medicalRecord.setBirth(DateUtil.stringDate2Date(patientCardInfo.getBirthday()));
                medicalRecord.setPatientCardNo(patientCardInfo.getCardNo());
                medicalRecord.setPayAmount(consultationInfoOrder.getPayAmount());
                medicalRecord.setBuyTime(consultationInfoOrder.getPayTime());
            }
            medicalRecordRepository.save(medicalRecord);
            //上传 主诉图片列表
            List<String> imgs = addMedicalRecordForm.getChiefComplaintImgPath();
            if (imgs != null && imgs.size() > 0) {
                int i = 0;
                for (String img : imgs) {
                    File file = new File();
                    file.setId(LocalStringUtil.getUUID());
                    file.setPath(img);
                    file.setBusinessId(medicalRecordId);
                    file.setSort(i++);
                    file.setType(0);//0是 主诉
                    fileRepository.save(file);
                }
            }
            //上传 意见图片列表
            List<String> opinionImgPath = addMedicalRecordForm.getOpinionImgPath();

            if (opinionImgPath != null && opinionImgPath.size() > 0) {
                int i = 0;
                for (String img : opinionImgPath) {
                    File file = new File();
                    file.setId(LocalStringUtil.getUUID());
                    file.setPath(img);
                    file.setBusinessId(medicalRecordId);
                    file.setSort(i++);
                    file.setType(1);//1是 意见
                    fileRepository.save(file);
                }
            }
            //绑定 用药医嘱
            List<ExhortItemForm> exhortList = addMedicalRecordForm.getExhortList();
            if(exhortList != null && exhortList.size() > 0){
                int i = 0;
                for(ExhortItemForm exhortItemForm : exhortList){
                    Exhort exhort = new Exhort();
                    BeanUtils.copyProperties(exhortItemForm, exhort);
                    exhort.setBusinessId(medicalRecordId);
                    exhort.setSort(i++);
                    exhort.setAddtime(System.currentTimeMillis() / 1000);
                    this.exhortRepository.save(exhort);
                }
            }

        }
        return consultationInfoOrder;
    }

    @Override
    public MedicalRecordInfoDTO medicalInfo(String id) {
        MedicalRecord medicalRecord = medicalRecordRepository.findFirstByConsultationId(id);
        MedicalRecordInfoDTO medicalRecordInfoDTO = new MedicalRecordInfoDTO();
        if(medicalRecord!=null){
            BeanUtils.copyProperties(medicalRecord,medicalRecordInfoDTO);
            String consultationId = medicalRecord.getConsultationId();
            ConsultationInfoOrder consultationInfoOrder = consultationInfoRepository.
                    findById(consultationId).orElseThrow(() -> new NormalException(ResultEnums.NOT_EXIST));
            medicalRecordInfoDTO.setPrescriptionId(consultationInfoOrder.getPrescriptionId());
            String medicalRecordId = medicalRecord.getId();
            List<File> files = fileRepository.findAllByBusinessIdOrderBySort(medicalRecordId);


            ArrayList<String> chiefComplaintImgPath = new ArrayList<>();
            ArrayList<String> opinionImgPath = new ArrayList<>();

            for(File file : files){
                if(file.getType() == 1){
                    opinionImgPath.add(file.getPath());
                }else{
                    chiefComplaintImgPath.add(file.getPath());
                }
            }

            medicalRecordInfoDTO.setChiefComplaintImgPath(chiefComplaintImgPath);
            medicalRecordInfoDTO.setOpinionImgPath(opinionImgPath);

            List<Exhort> exhorts = exhortRepository.findAllByBusinessIdOrderBySort(medicalRecordId);
            medicalRecordInfoDTO.setExhortList(exhorts);

            return medicalRecordInfoDTO;
        }
        return medicalRecordInfoDTO;
    }

    @Override
    public List<MedicalRecordBaseInfoDTO> list(String userId, String patientCardId) {
        List<ConsultationInfoOrder> consultationInfoOrders = null;
        if(StringUtils.isNotBlank(patientCardId)){
            consultationInfoOrders = this.consultationInfoRepository.findByPatientCardIdOrderByCreateTimeDesc(patientCardId);
        }else{
            consultationInfoOrders = this.consultationInfoRepository.findByPayAccountIdOrderByCreateTimeDesc(userId);
        }
        if(consultationInfoOrders != null && consultationInfoOrders.size() > 0){
            ArrayList<String> consultationInfoOrderIds = new ArrayList<>();
            for(ConsultationInfoOrder consultationInfoOrder : consultationInfoOrders){
                consultationInfoOrderIds.add(consultationInfoOrder.getId());
            }
            List<MedicalRecord> medicalRecords = medicalRecordRepository.findByConsultationIdIn(consultationInfoOrderIds);

            if(medicalRecords != null && medicalRecords.size() > 0){
                ArrayList<MedicalRecordBaseInfoDTO> medicalRecordBaseInfoDTOs = new ArrayList<>();
                for(MedicalRecord medicalRecord : medicalRecords){
                    medicalRecordBaseInfoDTOs.add(MedicalRecordBaseInfoDTO.builder()
                            .id(medicalRecord.getId())
                            .doctorName(medicalRecord.getDoctorName())
                            .createTime(medicalRecord.getAddTime())
                             .consultationId(medicalRecord.getConsultationId())
                                    .patientName(medicalRecord.getPatientName())
                                    .birthday(medicalRecord.getBirthday())
                                    .sex(medicalRecord.getSex())
                            .chiefComplaint(medicalRecord.getChiefComplaint()).build());
                }
                return medicalRecordBaseInfoDTOs;
            }
        }
        return null;
    }
}
